package com.gitee.netty.socket_demo;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 开发人员   YooLin1c
 * 编写日期   2018/7/21
 * 联系邮箱   401664157@qq.com
 * 作用描述
 */
@Slf4j
public class Client {
    private static final String HOST = "localhost";
    private static final int PORT = 8000;
    private static final int SLEEP_TIME = 5000;

    public static void main(String[] args) throws IOException {
        // 连接socket服务器端
        final Socket socket = new Socket(HOST, PORT);

        // 新启一个线程防止阻塞主线程
        new Thread(() -> {
            log.info("客户端启动成功");
            // 轮训
            while (true) {
                try {
                    // 客户端向服务端发送数据
                    OutputStream outputStream = socket.getOutputStream();
                    String message = "hello socket";
                    log.info("客户端发送数据:{}", message);
                    outputStream.write(message.getBytes());
                } catch (IOException e) {
                    log.error("客户端发送数据失败", e);
                }
                try {
                    Thread.sleep(SLEEP_TIME);
                } catch (InterruptedException e) {
                    log.error("客户端睡眠失败", e);
                }
            }

        }).start();
    }
}
